package com.jrx.anytxn.transaction.service.impl;

import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.feign.param.request.PartnerLimitAdjustmentReq;
import com.jrx.anytxn.feign.param.response.PartnerLimitAdjustmentRes;
import com.jrx.anytxn.feign.param.service.IAnyTxnParamService;
import com.jrx.anytxn.i18n.response.TxnRespResult;
import com.jrx.anytxn.param.entity.PmPartnerInfo;
import com.jrx.anytxn.param.entity.PrProductTable;
import com.jrx.anytxn.param.service.partner.IPmPartnerInfoService;
import com.jrx.anytxn.param.service.product.IProductTableService;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.service.IPartnerLimitRecoveryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class PartnerLimitRecoveryServiceImpl implements IPartnerLimitRecoveryService {

    private static final Logger logger = LoggerFactory.getLogger(PartnerLimitRecoveryServiceImpl.class);


    @Autowired
    private IProductTableService productTableService;
    @Autowired
    private IPmPartnerInfoService pmPartnerInfoService;
    @Lazy
    @Autowired
    private IAnyTxnParamService anyTxnParamService;


    @Override
    public void partnerLimitRecovery(String productId, String orgId, String tenantId, BigDecimal Amount,String seqNo) throws TxnBizException {
        PrProductTable product = productTableService.findProByProIdAndOrgId(productId,orgId,tenantId);

        //需要更新合作方额度的产品才做检查
        if(TransBizConstant.UPDATE_DEPOSIT_LIMIT_1.equals(product.getUpdateDepositLimit())&&
                null!=product.getPartnerId()){
            //获取合作方额度信息
            PmPartnerInfo pmPartnerInfo = pmPartnerInfoService.getByPartnerId(product.getTenantId(),product.getPartnerId());
            //更新合作方额度
            PartnerLimitAdjustmentReq req = new PartnerLimitAdjustmentReq();
            req.setSeqNo(seqNo);
            req.setAdjustmentType(TransBizConstant.ADJUSTMENT_TYPE_1);
            req.setAmout(Amount);
            req.setPartnerId(pmPartnerInfo.getPartnerId());
            req.setTenantId(pmPartnerInfo.getTenantId());
            TxnRespResult<PartnerLimitAdjustmentRes> res;
            try{
                res = anyTxnParamService.partnerLimitAdjustment(req);
            }catch (Exception e){
                logger.error("调用合作方额度调整接口出现异常",e);
                throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
            }

            if(null == res ||!TransBizConstant.ADJUSTMENT_STATUS_S.equals(res.getData().getSumStatus())){
                logger.error("调用合作方额度调整接口 更新失败");
                throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
            }
        }
    }
}
